//
//  MusicsData.m
//  AdultApp
//
//  Created by umina on 5/26/14.
//  Copyright (c) 2014 xyx. All rights reserved.
//

#import "MusicsData.h"
#import "Macro.h"
static int indexCurrentMusic = 0;    //当前歌曲索引

@implementation MusicsData

+(MusicsData*)sharedInstance{
    static MusicsData *sharedInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedInstance = [[MusicsData alloc] init];
    });
    return sharedInstance;
}

+(NSMutableArray *)loadAllMusics
{
    [[self sharedInstance]loadMusicData];
    [[self sharedInstance]loadMusicArtworks];
    return [self sharedInstance].arrMusic;
}

+(NSDictionary *)loadCurrentMusicInfo{
    [[self sharedInstance]loadMusicOtherInfo];
    NSDictionary *dicTemp = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[self sharedInstance].strArtist,[self sharedInstance].strAlbumName,[self sharedInstance].strTitle, nil]
                                                        forKeys:[NSArray arrayWithObjects:MUSIC_CURRENT_ARTIST,MUSIC_CURRENT_ALBUM,MUSIC_CURRENT_TITLE, nil]];
    return dicTemp;
}

+(NSString *)getProgressAudioPath{
    NSString *str = [NSString stringWithFormat:@"%@/%@.mp3",[[self sharedInstance]getSandBoxPathString],[[self sharedInstance].arrMusic objectAtIndex:indexCurrentMusic],nil];
    return str;
}

+(int)getIndexCutrentMusic
{
    return indexCurrentMusic;
}
+(void)setIndexCutrentMusic:(int)newValue{
    indexCurrentMusic = newValue;
}

+(void)delMusicByName:(NSString *)musicName{
    NSString *fileFullPath = [NSString stringWithFormat:@"%@/%@.mp3",[[self sharedInstance]getSandBoxPathString],musicName];
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    BOOL isExist = [fileMgr fileExistsAtPath:fileFullPath];
    if (isExist) {
        NSError *err;
        [fileMgr removeItemAtPath:fileFullPath error:&err];
    }
    
    [self loadAllMusics];
}

#pragma mark - About Music Resource - Load to Var

- (void)loadMusicData{
    NSFileManager *fileManage = [NSFileManager defaultManager];
    NSArray *files = [fileManage subpathsAtPath:[self getSandBoxPathString]];
    if (!_arrMusic) {
    _arrMusic = [[NSMutableArray alloc]init];
    }else{
        [_arrMusic removeAllObjects];
    }
    
    
    if (files.count!=0)
    {
        for (int num = 0; num < files.count; num++)
        {
            NSString *strSongFileName = [files objectAtIndex:num];
            if ([[strSongFileName pathExtension]isEqualToString:@"mp3"])
            {
                NSUInteger i = strSongFileName.length-4;
                NSRange range={0,i};
                strSongFileName = [strSongFileName substringWithRange:range];
                NSLog(@"+++%@",strSongFileName);
                [_arrMusic addObject:strSongFileName];
            }
        }
    }
}
- (void)loadMusicOtherInfo{
    BOOL artistChanged = NO;
    BOOL albumNameChanged = NO;
    BOOL titleChanged = NO;
    
    AVURLAsset *mp3Asset=[AVURLAsset URLAssetWithURL:[self getMusicPathURL] options:nil];
    for (NSString *format in [mp3Asset availableMetadataFormats])
    {
        for (AVMetadataItem *metadataItem in [mp3Asset metadataForFormat:format])
        {
            if ([metadataItem.commonKey isEqualToString:@"artist"])
            {
                _strArtist = (NSString*)metadataItem.value;
                artistChanged = YES;
            }
            if ([metadataItem.commonKey isEqualToString:@"albumName"])
            {
                _strAlbumName = (NSString*)metadataItem.value;
                albumNameChanged = YES;
            }
            if ([metadataItem.commonKey isEqualToString:@"title"])
            {
                _strTitle = (NSString*)metadataItem.value;
                titleChanged = YES;
            }
        }
    }
    
    if (!artistChanged) {
        _strArtist = @"UnKnown Arttist";
    }
    
    if (!albumNameChanged) {
        _strAlbumName= @"Unknown Album";
    }
    
    if (!titleChanged) {
        _strTitle = @"Unknown Song Name";
    }
}

- (void)loadMusicArtworks{
    if (!_arrMusicArtwork) {
        _arrMusicArtwork = [[NSMutableArray alloc]init];
    }else{
        [_arrMusicArtwork removeAllObjects];
    }
    if (!_arrMusicArtist) {
        _arrMusicArtist = [[NSMutableArray alloc]init];
    }else{
        [_arrMusicArtist removeAllObjects];
    }
    if (!_arrMusicTime) {
        _arrMusicTime = [[NSMutableArray alloc]init];
    }else{
        [_arrMusicTime removeAllObjects];
    }
    
    for (NSString *strName in self.arrMusic){
        NSString *musicPath=[[NSString alloc]initWithFormat:@"%@/%@.mp3",[self getSandBoxPathString],strName,nil];
        NSURL *url = [NSURL fileURLWithPath:musicPath];
     
        BOOL foundArtwork = NO;
        BOOL foundArtist = NO;
        
        AVURLAsset *mp3Asset=[AVURLAsset URLAssetWithURL:url options:nil];
        for (NSString *format in [mp3Asset availableMetadataFormats])
        {
            for (AVMetadataItem *metadataItem in [mp3Asset metadataForFormat:format])
            {
                if ([metadataItem.commonKey isEqualToString:@"artwork"]) {
                    NSData *data = [(NSDictionary *)metadataItem.value objectForKey:@"data"];
                    [self.arrMusicArtwork addObject:data];
                    foundArtwork = YES;
                }
                
                if ([metadataItem.commonKey isEqualToString:@"artist"]) {
                    NSString *artist = (NSString *)metadataItem.value;
                    [self.arrMusicArtist addObject:artist];
                    foundArtist = YES;
                    break;
                }
            }
        }
        
        if (!foundArtwork) {
            NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Img_MusicPlay_NoImg" ofType:@"png"];
            NSData*  data=[NSData dataWithContentsOfFile:filePath];
            [self.arrMusicArtwork addObject:data];
        }
        
        if(!foundArtist)
        {
          [self.arrMusicArtwork addObject:@"未知歌手"];
        }
        
        CMTime durationTime = mp3Asset.duration;
        NSInteger duration = CMTimeGetSeconds(durationTime);
        [self.arrMusicTime addObject:[NSString stringWithFormat:@"%ld",(long)duration]];
        
    }
}

#pragma mark - 从音乐束中加载音乐到document
+(void)copyFileDatabase
{
    NSString *documentFolderPath = [[self sharedInstance]getSandBoxPathString];
    NSString *bundlePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingString:MYBUNDLE_NAME];
    
    NSString *strMusicName;
    for (int index = 0; index<4; index++) {
        switch (index) {
            case 0:
                strMusicName = @"Default_01.mp3";
                break;
            case 1:
                strMusicName = @"Default_02.mp3";
                break;
            case 2:
                strMusicName = @"Default_03.mp3";
                break;
            case 3:
                strMusicName = @"Default_04.mp3";
                break;
            default:
                break;
        }
        
        NSString *strTargetPath = [NSString stringWithFormat:@"%@/%@",documentFolderPath,strMusicName];
        NSString *strSourcePath = [NSString stringWithFormat:@"%@/%@",bundlePath,strMusicName];
        
        NSError *error = nil;
        [[NSFileManager defaultManager]copyItemAtPath:strSourcePath
                                               toPath:strTargetPath
                                                error:&error];
        if (error) {
            NSLog(@"error = %@",error);
        }

    }
    
}

#pragma mark - About Music Resource - Get Data
- (NSString *)getSandBoxPathString{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return documentsDirectory;
}
- (NSURL *)getMusicPathURL{
    NSURL *url=nil;
    if (indexCurrentMusic < _arrMusic.count)
    {
        NSString *musicPath=[[NSString alloc]initWithFormat:@"%@/%@.mp3",[self getSandBoxPathString],[_arrMusic objectAtIndex:indexCurrentMusic],nil];
        
        url = [NSURL fileURLWithPath:musicPath];
    }
    return url;
}


@end
